package compiler

import (
	"JudgeClient/client"
	"JudgeClient/global"
	"errors"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
)

func GetSim(listSid []int64, sid int64, language string) ([]byte, error) {
	var extension string
	switch language {
	case "c":
		{
			extension = "c"
		}
	case "cpp":
		{
			extension = "cc"
		}
	case "java":
		{
			extension = "java"
		}
	default:
		err := errors.New("invalid language")
		global.Logger.Errorf("sid:%v,invalid language", sid)
		return nil, err
	}

	simTestDir := filepath.Join(global.Conf.Path.WorkDir, global.Conf.Path.SimDir, strconv.Itoa(int(sid)))

	cmd := exec.Command("mkdir", "-p", simTestDir)
	err := cmd.Run()
	if err != nil {
		global.Logger.Errorf("make sim testDir err:%v", err)
		return nil, err
	}
	defer os.RemoveAll(simTestDir)

	codeFilePath := filepath.Join(simTestDir, strconv.Itoa(int(sid)), "main."+extension)
	client.JClient.DownLoadSubCode(sid, codeFilePath)

	var count int

	subDir := filepath.Join(simTestDir + "test_sub")

	for i := range listSid {
		simSid := listSid[i]

		if simSid != sid {
			filepath := filepath.Join(subDir, strconv.Itoa(int(simSid)), "main."+extension)
			client.JClient.DownLoadSubCode(simSid, filepath)
			count++
		}
	}

	cmd = exec.Command(filepath.Join(global.Conf.Path.WorkDir, "sim.sh"), simTestDir, extension)

	if err = cmd.Run(); err != nil {
		global.Logger.Errorf("sim file read error,err:%v", err)
		return nil, err
	}

	simFilePath := filepath.Join(simTestDir, "simFile")
	if _, err = os.Stat(simFilePath); err != nil {
		global.Logger.Errorf("sim file err:%v", err)
		return nil, err
	}

	simInfo, err := os.ReadFile(simFilePath)
	if err != nil {
		global.Logger.Errorf("sim file read error,err:%v", err)
		return nil, err
	}

	return simInfo, err
}
